package com.example.producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <h1> 发送延时消息 <h1>
 *
 * @author 魏如元
 * @since 2022/7/8
 */
@Service
public class DelayProducer {

    // 延时消息等级
    private final String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";

    @Value("${rocketmq.name-server}")
    private String nameServer;

    public void delayProducer() throws Exception {
        // 实例化一个生产者来生产消息
        DefaultMQProducer producer = new DefaultMQProducer("delay-producer");
        producer.setNamesrvAddr(nameServer);
        // 启动生产者
        producer.start();
        int totalMessagesToSend = 100;
        for (int i = 0; i < totalMessagesToSend; i++) {
            Message message = new Message("broker-delay",("I'm delay message - "+i).getBytes());
            // 设置延时等级 为3 这个消息将在10s之后发送
            message.setDelayTimeLevel(3);
            // 发消息
            producer.send(message);
        }
        // 关闭生产者
        producer.shutdown();
    }
}
